var express = require('express');
var pool = require('../mysql');
var router = express.Router();
var fs = require('fs');
var pathLib = require('path'); 
var multer  = require('multer');//这是一个处理上传文件的模块，将其引入;
var upload = multer({ dest: './public/upload' });

//添加页
router.route('/')
  .get(function(req, res, next) {
    let name = req.cookies.user;
    if(name == 'admin'){
      pool.query(`select * from label`, function (err, la_result) {
        if(la_result){
          res.render('add', { title: '添加', label: la_result});
        }else{
          res.render('add', { title: '添加', label: [] });
        }
      });
    }else{
      res.send('抱歉,您没有权限');
    }
  })
  .post(upload.any(), function(req, res, next){
    //文件上传
    for(let i=0; i<req.files.length;i++){
      let newname = req.files[i].path + pathLib.parse( req.files[i].originalname).ext;
      fs.rename( req.files[i].path, newname );
    }
    //添加组件
    let {details = '',hidTags = ''} = req.body;
    let url = 'upload/' + req.files[0].filename + pathLib.parse( req.files[0].originalname).ext;
    let project = 'upload/' + req.files[1].filename + pathLib.parse( req.files[1].originalname).ext;
    pool.query(`INSERT INTO component ( details, url, project ) VALUES ( '${details}', '${url}', '${project}' );`, function (err, result) {
      if(err){
        res.send('组件添加失败');
        return false;
      }else{
        //插入标签
        let cid = result.insertId;
        let _hidTags = hidTags.split(',') || [];
        for(let i=0; i<_hidTags.length;i++){
          pool.query(`select * from label where name = '${_hidTags[i]}'`, function (err, la_result) {
            if(la_result.length > 0){//数据库里有这个标签
              let {id = ''} = la_result[0]; //标签id
              pool.query(`INSERT INTO component_label_relation ( cid, lid ) VALUES ( '${cid}', '${id}' );`, function (err, result) {
                if(err){
                    console.log('关系表插入失败');
                }else{
                  if(i >= _hidTags.length -1){
                    res.send(`添加成功，二秒后返回添加页
                      <script>
                        setTimeout(() => {
                          window.location.href='/add';
                        }, 2000);
                      </script>
                    `);
                  }
                }
              });
            }else{//数据库里没有这个标签
              pool.query(`INSERT INTO label ( name ) VALUES ( '${_hidTags[i]}' );`, function (err, result) {
                if(err){
                    console.log('label表插入失败');
                }else{
                  let lid = result.insertId;//标签id
                  pool.query(`INSERT INTO component_label_relation ( cid, lid ) VALUES ( '${cid}', '${lid}' );`, function (err, result) {
                    if(err){
                        console.log('关系表插入失败');
                    }else{
                      if(i >= _hidTags.length -1){
                        res.send(`添加成功，二秒后返回添加页
                          <script>
                            setTimeout(() => {
                              window.location.href='/add';
                            }, 2000);
                          </script>
                        `);
                      }
                    }
                  });
                }
              });
            }
          });
        }
      }
    });
  });
module.exports = router;